/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

/*
 * ContentEditScrean.java
 *
 * Created on 11.09.2012, 14:18:50
 */

package org.opu.odg.m_ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import org.apache.commons.lang.text.StrSubstitutor;
import org.opu.odg.dg.incomingdata.DatabaseSettings;
import org.opu.odg.m_ui.beans.ContentBean;
import org.opu.odg.m_ui.beans.ContentBean.ContentType;
import org.opu.odg.m_ui.beans.VariableBean;

/**
 *
 * @author yura
 */
public class ContentEditScrean extends javax.swing.JDialog {

    private ResourceBundle bundle = ResourceBundle.getBundle("org.opu.odg.m_ui.Bundle");
    private VarChangesListener varChangesListener;
    private ContentBean editingContent;

    /** Creates new form ContentEditScrean */
    public ContentEditScrean(java.awt.Frame parent, boolean modal,
            VarChangesListener varChangesListener, ContentBean editingContent) {
        super(parent, modal);
        this.varChangesListener = varChangesListener;
        this.editingContent = editingContent;
        initComponents();

        ContentType cType = editingContent.getContentType();
        if (cType != null) {
            contentTypeCmBx.setSelectedItem(new ContentTypeUI(cType));
            dbSqlText.setText(notNullStr(editingContent.getQuery()));
            DatabaseSettings dbSet = editingContent.getDatabaseSettings();
            if (dbSet != null) {
                dbUrlTxtBx.setText(notNullStr(dbSet.getUrl()));
                dbDriverTxtBx.setText(notNullStr(dbSet.getDriver()));
                dbUserTxtBx.setText(notNullStr(dbSet.getUser()));
                dbPswdTxtBx.setText(notNullStr(dbSet.getPswd()));
            }
        }

        describesExternalTagChBx.setSelected(editingContent.isDescribesExternalTag());

        contentTypeCmBx.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                reset();
            }
        });
        reset();

        setLocationRelativeTo(parent);
    }

    private void reset() {
        dbConfPanel.setVisible(getSelectedContentType() == ContentType.Database);
    }

    private ContentType getSelectedContentType() {
        return ((ContentTypeUI) contentTypeCmBx.getSelectedItem()).contentType;
    }

    private List<String> completeData() {
        final List<String> list = new ArrayList<String>();
        editingContent.setContentType(getSelectedContentType());
        if (editingContent.getContentType() == ContentType.Database) {
            editingContent.setQuery(dbSqlText.getText());
            editingContent.setDatabaseSettings(new DatabaseSettings(
                    dbUrlTxtBx.getText(), dbDriverTxtBx.getText(),
                    notEmptyStr(dbUserTxtBx.getText()),
                    notEmptyStr(dbPswdTxtBx.getText())));
            
            StrSubstitutor.replace(dbSqlText.getText(), new AbstractMap() {
                public Set entrySet() { return null;}
                public Object get(Object key) {return list.add(key.toString());}
            });
        }
        editingContent.setDescribesExternalTag(describesExternalTagChBx.isSelected());
        return list;
    }

    private String notEmptyStr(String str) {
        return str.trim().isEmpty() ? null : str;
    }

    private String notNullStr(String str) {
        return str == null ? "" : str;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bottomPanel = new javax.swing.JPanel();
        cancelBtn = new javax.swing.JButton();
        okBtn = new javax.swing.JButton();
        contentPanel = new javax.swing.JPanel();
        topPanel = new javax.swing.JPanel();
        describesExternalTagChBx = new javax.swing.JCheckBox();
        contetntTypePanel = new javax.swing.JPanel();
        contentTypeLbl = new javax.swing.JLabel();
        contentTypeCmBx = new javax.swing.JComboBox();
        centerPanel = new javax.swing.JPanel();
        dbConfPanel = new javax.swing.JPanel();
        dbUrlLbl = new javax.swing.JLabel();
        dbUrlTxtBx = new javax.swing.JTextField();
        dbDriverLbl = new javax.swing.JLabel();
        dbDriverTxtBx = new javax.swing.JTextField();
        dbUserLbl = new javax.swing.JLabel();
        dbUserTxtBx = new javax.swing.JTextField();
        dbPswdLbl = new javax.swing.JLabel();
        dbPswdTxtBx = new javax.swing.JTextField();
        dbSqlScrol = new javax.swing.JScrollPane();
        dbSqlText = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        cancelBtn.setText(bundle.getString("cancel")); // NOI18N
        cancelBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelBtnActionPerformed(evt);
            }
        });
        bottomPanel.add(cancelBtn);

        okBtn.setText(bundle.getString("Save")); // NOI18N
        okBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okBtnActionPerformed(evt);
            }
        });
        bottomPanel.add(okBtn);

        getContentPane().add(bottomPanel, java.awt.BorderLayout.PAGE_END);

        contentPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("template.edit.content") + " \"" + editingContent.getName() + "\""));
        contentPanel.setLayout(new java.awt.BorderLayout(0, 10));

        topPanel.setLayout(new javax.swing.BoxLayout(topPanel, javax.swing.BoxLayout.PAGE_AXIS));

        describesExternalTagChBx.setText(bundle.getString("template.edit.content.describesExternalTag")); // NOI18N
        describesExternalTagChBx.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                describesExternalTagChBxActionPerformed(evt);
            }
        });
        topPanel.add(describesExternalTagChBx);

        contetntTypePanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        contentTypeLbl.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        contentTypeLbl.setText(bundle.getString("template.edit.content.type")); // NOI18N
        contetntTypePanel.add(contentTypeLbl, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 130, 25));

        contentTypeCmBx.setModel(new javax.swing.DefaultComboBoxModel(new Object[] {new ContentTypeUI(ContentType.Custom), new ContentTypeUI(ContentType.Database)}));
        contetntTypePanel.add(contentTypeCmBx, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 0, 350, -1));

        topPanel.add(contetntTypePanel);

        contentPanel.add(topPanel, java.awt.BorderLayout.PAGE_START);

        centerPanel.setLayout(new javax.swing.BoxLayout(centerPanel, javax.swing.BoxLayout.LINE_AXIS));

        dbUrlLbl.setFont(dbUrlLbl.getFont().deriveFont((dbUrlLbl.getFont().getStyle() | java.awt.Font.ITALIC)));
        dbUrlLbl.setText(bundle.getString("template.edit.content.db_url")); // NOI18N

        dbUrlTxtBx.setFont(dbSqlText.getFont());

        dbDriverLbl.setFont(dbDriverLbl.getFont().deriveFont((dbDriverLbl.getFont().getStyle() | java.awt.Font.ITALIC)));
        dbDriverLbl.setText(bundle.getString("template.edit.content.driver_class_name")); // NOI18N

        dbDriverTxtBx.setFont(dbSqlText.getFont());

        dbUserLbl.setFont(dbUserLbl.getFont().deriveFont((dbUserLbl.getFont().getStyle() | java.awt.Font.ITALIC)));
        dbUserLbl.setText(bundle.getString("template.edit.content.db_user")); // NOI18N

        dbUserTxtBx.setFont(dbSqlText.getFont());

        dbPswdLbl.setFont(dbPswdLbl.getFont().deriveFont((dbPswdLbl.getFont().getStyle() | java.awt.Font.ITALIC)));
        dbPswdLbl.setText(bundle.getString("template.edit.content.db_pswd")); // NOI18N

        dbPswdTxtBx.setFont(dbSqlText.getFont());

        dbSqlScrol.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("template.edit.content.sql"))); // NOI18N

        dbSqlText.setColumns(20);
        dbSqlText.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
        dbSqlText.setRows(5);
        dbSqlScrol.setViewportView(dbSqlText);

        javax.swing.GroupLayout dbConfPanelLayout = new javax.swing.GroupLayout(dbConfPanel);
        dbConfPanel.setLayout(dbConfPanelLayout);
        dbConfPanelLayout.setHorizontalGroup(
            dbConfPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dbConfPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(dbConfPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dbSqlScrol, javax.swing.GroupLayout.DEFAULT_SIZE, 472, Short.MAX_VALUE)
                    .addGroup(dbConfPanelLayout.createSequentialGroup()
                        .addGroup(dbConfPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(dbPswdLbl, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(dbUserLbl, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(dbDriverLbl, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(dbUrlLbl, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(dbConfPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(dbPswdTxtBx, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                            .addComponent(dbUserTxtBx, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                            .addComponent(dbDriverTxtBx, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                            .addComponent(dbUrlTxtBx, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE))))
                .addContainerGap())
        );
        dbConfPanelLayout.setVerticalGroup(
            dbConfPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(dbConfPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(dbConfPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dbUrlLbl)
                    .addComponent(dbUrlTxtBx, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(dbConfPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dbDriverLbl)
                    .addComponent(dbDriverTxtBx, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(dbConfPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dbUserLbl)
                    .addComponent(dbUserTxtBx, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(dbConfPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(dbPswdLbl)
                    .addComponent(dbPswdTxtBx, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(dbSqlScrol, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE))
        );

        centerPanel.add(dbConfPanel);

        contentPanel.add(centerPanel, java.awt.BorderLayout.CENTER);

        getContentPane().add(contentPanel, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelBtnActionPerformed
        dispose();
    }//GEN-LAST:event_cancelBtnActionPerformed

    private void okBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okBtnActionPerformed
        List<String> futureVars = completeData();
        editingContent.setConfigured(true);
        for (String string : futureVars) {
            if (editingContent.getVariable(string) == null) {
                varChangesListener.applyVarChanges(null,
                        new VariableBean(string, editingContent, editingContent));
            }
        }
        varChangesListener.onContentChanged(editingContent);
        dispose();
    }//GEN-LAST:event_okBtnActionPerformed

    private void describesExternalTagChBxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_describesExternalTagChBxActionPerformed
        editingContent.setDescribesExternalTag(describesExternalTagChBx.isSelected());
    }//GEN-LAST:event_describesExternalTagChBxActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel bottomPanel;
    private javax.swing.JButton cancelBtn;
    private javax.swing.JPanel centerPanel;
    private javax.swing.JPanel contentPanel;
    private javax.swing.JComboBox contentTypeCmBx;
    private javax.swing.JLabel contentTypeLbl;
    private javax.swing.JPanel contetntTypePanel;
    private javax.swing.JPanel dbConfPanel;
    private javax.swing.JLabel dbDriverLbl;
    private javax.swing.JTextField dbDriverTxtBx;
    private javax.swing.JLabel dbPswdLbl;
    private javax.swing.JTextField dbPswdTxtBx;
    private javax.swing.JScrollPane dbSqlScrol;
    private javax.swing.JTextArea dbSqlText;
    private javax.swing.JLabel dbUrlLbl;
    private javax.swing.JTextField dbUrlTxtBx;
    private javax.swing.JLabel dbUserLbl;
    private javax.swing.JTextField dbUserTxtBx;
    private javax.swing.JCheckBox describesExternalTagChBx;
    private javax.swing.JButton okBtn;
    private javax.swing.JPanel topPanel;
    // End of variables declaration//GEN-END:variables

    class ContentTypeUI implements Serializable{
        final ContentType contentType;
        final String title;

        ContentTypeUI(ContentType contentType) {
            this.contentType = contentType;
            title = bundle.getString("contentType." + contentType);
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final ContentTypeUI other = (ContentTypeUI) obj;
            if (this.contentType != other.contentType) {
                return false;
            }
            return true;
        }

        @Override
        public int hashCode() {
            int hash = 7;
            hash = 71 * hash + (this.contentType != null ? this.contentType.hashCode() : 0);
            return hash;
        }

        @Override
        public String toString() {
            return title;
        }
    }

}
